package com.tencent.mlvb.apilive.ui;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tencent.live2.V2TXLivePusherObserver;
import com.tencent.mlvb.apilive.ExitApplication;
import com.tencent.mlvb.apilive.GenerateTestUserSig;
import com.tencent.mlvb.apilive.R;
import com.tencent.mlvb.apilive.bean.EndLiveEvent;
import com.tencent.mlvb.apilive.bean.IsLiveEvent;
import com.tencent.mlvb.apilive.bean.LivePlanBean;
import com.tencent.mlvb.apilive.bean.StartLiveEvent;
import com.tencent.mlvb.apilive.databinding.ActivityLivePrepareBinding;
import com.tencent.mlvb.apilive.network.ApiRequestService;
import com.tencent.mlvb.apilive.network.CallBackLis;
import com.tencent.mlvb.apilive.network.HttpCall;
import com.tencent.mlvb.apilive.network.ResponseModel;
import com.tencent.mlvb.apilive.network.RetrofitHelper;
import com.tencent.mlvb.apilive.utils.DateUtil;
import com.tencent.mlvb.apilive.utils.Md5Util;
import com.tencent.live2.V2TXLiveDef;
import com.tencent.live2.V2TXLivePusher;
import com.tencent.live2.impl.V2TXLivePusherImpl;
import com.tencent.mlvb.apilive.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;

public class LivePrepareActivtiy extends AppCompatActivity {
    private ActivityLivePrepareBinding binding;
    private TaskAdapter taskAdapter;
    private Intent mIntent;
    private boolean isOpen;
    private String code;
    private int type;
    private String uavId;
    private LivePlanBean currentLivePlanBean;//任务
    private LivePlanBean currentLive;//当前直播
    private V2TXLivePusher mLivePusher;
    private boolean isLive = false;
    private Intent popupServiceIntent;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         binding = ActivityLivePrepareBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ExitApplication.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
        initData();
        initView();
    }

    private void initData(){
        //获取任务列表
        type = getIntent().getIntExtra("type",0);
        code = getIntent().getStringExtra("code");
        uavId = getIntent().getStringExtra("uavId");
        if (type == 1){
            currentLive = (LivePlanBean)getIntent().getSerializableExtra("livePlanBean");
            IsCanDrawOverlays();
        }else {
            getExport();
        }
    }
    private void initView(){
        popupServiceIntent = new Intent(this, PopupService.class);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        binding.recyclerview.setLayoutManager(linearLayoutManager);
        taskAdapter = new TaskAdapter(this, R.layout.item_task);
        binding.recyclerview.setAdapter(taskAdapter);
        binding.tvPrepare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断是否有权限
                showFloatView();
                moveTaskToBack(true);
                boolean isLive1 = SpUtils.getBoolean(getApplicationContext(), "isLive", false);
                if (isLive1){
                    Toast.makeText(LivePrepareActivtiy.this, "当前正在直播", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (currentLivePlanBean == null){
                    Toast.makeText(LivePrepareActivtiy.this, "选择直播任务", Toast.LENGTH_SHORT).show();
                    return;
                }
                IsCanDrawOverlays();
            }
        });
        taskAdapter.setItemOnClickListener(new TaskAdapter.ItemOnClickListener() {
            @Override
            public void itemOnClick(int position) {
               List<LivePlanBean> list = taskAdapter.items;
                currentLivePlanBean = list.get(position);
                for (int i = 0; i < list.size(); i++) {
                    if (i == position){
                        list.get(i).setSelect(true);
                    }else {
                        list.get(i).setSelect(false);
                    }
                }

                taskAdapter.setData(list);
            }
        });
    }

    private void IsCanDrawOverlays(){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
            return;
        } else {
            if (Build.VERSION.SDK_INT >= 23) {
                if (Settings.canDrawOverlays(this)) {
                    //添加直播任务
                    if (type == 0){
                        addLive();
                    }
                    showFloatView();

                    isOpen = true;
                    moveTaskToBack(true);
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    startActivityForResult(intent, 100);
                }
            } else {
                showFloatView();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
      boolean  isLive1 = SpUtils.getBoolean(getApplicationContext(), "isLive", false);
        if (isLive1){
            moveTaskToBack(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void startLive(StartLiveEvent event){
        setLvie();
        startLive();
        isLive = true;
        SpUtils.putBoolean(getApplication(),"isLive",true);
        FloatView.setType(isLive);
        Toast.makeText(LivePrepareActivtiy.this, "开启直播", Toast.LENGTH_SHORT).show();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void endLive(EndLiveEvent event){
                    hideFloatView();
                    endLive();
        isLive = false;
        SpUtils.putBoolean(getApplication(),"isLive",false);
        Toast.makeText(LivePrepareActivtiy.this, "结束直播", Toast.LENGTH_SHORT).show();
    }
    /**
     * 显示悬浮窗
     */
    private void showFloatView() {
        SpUtils.putBoolean(getApplication(),"isLive",false);
        FloatView.showFloatView(getApplication(), R.layout.layout_float_view);
        FloatView.setOnClickListener(new FloatView.OnClickListener() {
            @Override
            public void onClick(View view) {
                isLive = SpUtils.getBoolean(getApplication(),"isLive",false);
                popupServiceIntent.putExtra("isLive",isLive);
                startService(popupServiceIntent);
            }
        });
    }

    /**
     * 隐藏悬浮窗
     */
    public void hideFloatView(){
        SpUtils.putBoolean(getApplication(),"isLive",false);
        FloatView.hideFloatView();
    }


    private void getExport(){

        Map<String,String> hashMap = new LinkedHashMap<>();
        String currDate = DateUtil.getCurrDate("yyyy-MM-dd");
        hashMap.put("actionDateStr", currDate);
        hashMap.put("jobRegionCode", code);
        String mapToMD5String = Md5Util.getMapToMD5String(hashMap);

        Observable<ResponseModel<List<LivePlanBean>>> observable = RetrofitHelper.getInstance().getRetrofit().create(ApiRequestService.class).export(currDate,code,mapToMD5String);
        HttpCall.doCall(this, observable, new CallBackLis<List<LivePlanBean>>(){
            @Override
            public void onSuccess(String method, List<LivePlanBean> list) {
                taskAdapter.setData(list);
            }

            @Override
            public void onFailure(String method, String error) {

            }
        }, null);
    }

    private void addLive(){
        Map<String,String> hashMap = new LinkedHashMap<>();
        hashMap.put("jobRegionCode", code);
        hashMap.put("pipelinesTaskId", currentLivePlanBean.getId()+"");
        hashMap.put("uavId", uavId);
        String mapToMD5String = Md5Util.getMapToMD5String(hashMap);

        Observable<ResponseModel<LivePlanBean>> observable = RetrofitHelper.getInstance().getRetrofit().create(ApiRequestService.class).addLive(code,currentLivePlanBean.getId()+"",uavId,mapToMD5String);
        HttpCall.doCall(this, observable, new CallBackLis<LivePlanBean>(){
            @Override
            public void onSuccess(String method, LivePlanBean bean) {
                currentLive = bean;
            }

            @Override
            public void onFailure(String method, String error) {

            }
        }, null);
    }

    private void setLvie(){
        mLivePusher = new V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP);
        // 根据推流协议传入对应的 URL 即可启动推流， RTMP 协议以 rtmp:// 开头，该协议不支持连麦
//        String url = "rtmp://com.tencent.mlvb.apilive/live/streamid?txSecret=xxxxx&txTime=xxxxxxxx";
        // 根据推流协议传入对应的 URL 即可启动推流， RTC 协议以 trtc:// 开头，该协议支持连麦
//        String url = "trtc://cloud.tencent.com/push/streamid?sdkappid=1400188888&userId=A&usersig=xxxxx";
        mLivePusher.setObserver(new V2TXLivePusherObserver() {
            @Override
            public void onError(int code, String msg, Bundle extraInfo) {
                super.onError(code, msg, extraInfo);
                Log.e("推流状态:",msg+extraInfo);
            }
        });
        mLivePusher.stopMicrophone();//禁止麦克风
        mLivePusher.startScreenCapture();//开启屏幕采集
        //设置推流视频编码参数
        V2TXLiveDef.V2TXLiveVideoEncoderParam v2TXLiveVideoEncoderParam = new V2TXLiveDef.V2TXLiveVideoEncoderParam(V2TXLiveDef.V2TXLiveVideoResolution.V2TXLiveVideoResolution960x540);
        v2TXLiveVideoEncoderParam.videoResolutionMode = V2TXLiveDef.V2TXLiveVideoResolutionMode.V2TXLiveVideoResolutionModeLandscape;
        v2TXLiveVideoEncoderParam.videoResolution = V2TXLiveDef.V2TXLiveVideoResolution.V2TXLiveVideoResolution960x540;
        mLivePusher.setVideoQuality(v2TXLiveVideoEncoderParam);
//        mLivePusher.setVideoQuality(V2TXLiveDef.V2TXLiveVideoResolution.V2TXLiveVideoResolution960x540, V2TXLiveDef.V2TXLiveVideoResolutionMode.V2TXLiveVideoResolutionModeLandscape);
        //推流地址
        String pushUrl = "rtmp://" + GenerateTestUserSig.PUSH_DOMAIN + File.separator + "live" + File.separator + currentLive.getStreamId()
                + GenerateTestUserSig.getSafeUrl(currentLive.getStreamId());
//        String pushUrl = "rtmp://209667.push.tlivecloud.com/live/1740808812065?txSecret=714d91eae636d07c06243ea4b9d1fa38&txTime=67C54A36";
        int ret = mLivePusher.startPush(pushUrl);
        Log.e("推流:",pushUrl);
        Log.e("推流是否正常:",ret+"");//0正常
    }

    private void startLive(){

        Map<String,String> hashMap = new LinkedHashMap<>();
        hashMap.put("id", currentLive.getId()+"");
        String mapToMD5String = Md5Util.getMapToMD5String(hashMap);

        Observable<ResponseModel<Object>> observable = RetrofitHelper.getInstance().getRetrofit().create(ApiRequestService.class).startLive(currentLive.getId()+"",mapToMD5String);
        HttpCall.doCall(LivePrepareActivtiy.this, observable, new CallBackLis<Object>() {
            @Override
            public void onSuccess(String method, Object content) {

            }

            @Override
            public void onFailure(String method, String error) {

            }
        }, null);
    }

    private void endLive(){

        Map<String,String> hashMap = new LinkedHashMap<>();
        hashMap.put("id", currentLive.getId()+"");
        String mapToMD5String = Md5Util.getMapToMD5String(hashMap);

        Observable<ResponseModel<Object>> observable = RetrofitHelper.getInstance().getRetrofit().create(ApiRequestService.class).endLive(currentLive.getId()+"",mapToMD5String);
        HttpCall.doCall(LivePrepareActivtiy.this, observable, new CallBackLis<Object>() {
            @Override
            public void onSuccess(String method, Object content) {
                if (mLivePusher == null){
                    mLivePusher = new V2TXLivePusherImpl(LivePrepareActivtiy.this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP);
                }
                mLivePusher.stopScreenCapture();
                mLivePusher.stopPush();
                mLivePusher.release();
                ExitApplication.getInstance().exit();
            }

            @Override
            public void onFailure(String method, String error) {

            }
        }, null);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (Settings.canDrawOverlays(this)) {
                IsCanDrawOverlays();
            } else {
                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 101) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以开始录制
                IsCanDrawOverlays();
            } else {
                // 权限被拒绝，给出提示或处理逻辑
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
//        hideFloatView();
    }
}
